package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.FileUploadExceeption;
import com.sky.properties.AliyunOSSProperties;
import com.sky.result.Result;
import com.sky.utils.AliyunOSSUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
public class UploadController {
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) {
        try {
            log.info("文件上传");
            byte[] content = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID()+extName;
            String url = AliyunOSSUtils.upload(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getBucketName(), content, fileName);
            return Result.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            new FileUploadExceeption(MessageConstant.UPLOAD_FAILED);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
